/**
 * author: Di (微信小程序开发工程师)
 * organization: WeAppDev(微信小程序开发论坛)(http://weappdev.com)
 *               垂直微信小程序开发交流社区
 * 
 * github地址: https://github.com/icindy/wxParse
 * 
 * for: 微信小程序富文本解析
 * detail : http://weappdev.com/t/wxparse-alpha0-1-html-markdown/184
 */

/**
 * utils函数引入
 **/
import showdown from './showdown.js';
import HtmlToJson from './html2json.js';
/**
 * 配置及公有属性
 **/
var realWindowWidth = 0;
var realWindowHeight = 0;
wx.getSystemInfo({
  success: function (res) {
    realWindowWidth = res.windowWidth
    realWindowHeight = res.windowHeight
  }
})
/**
 * 主函数入口区
 **/
function wxParse(bindName = 'wxParseData', type='html', data='<div class="color:red;">数据不能为空</div>', target,imagePadding) {
  var that = target;
  var transData = {};//存放转化后的数据
  if (type == 'html') {
    console.log(data)
    transData = HtmlToJson.html2json(data, bindName);
    console.log(transData)
    //console.log(JSON.stringify(transData, ' ', ' '));
  } else if (type == 'md' || type == 'markdown') {
    var converter = new showdown.Converter();
    var html = converter.makeHtml(data);
    transData = HtmlToJson.html2json(html, bindName);
    //console.log(JSON.stringify(transData, ' ', ' '));
  }
  transData.view = {};
  transData.view.imagePadding = 0;
  if(typeof(imagePadding) != 'undefined'){
    transData.view.imagePadding = imagePadding
  }
  var bindData = {};
  bindData[bindName] = transData;
 // console.log(bindData);
  //console.log(bindData.article.nodes);
  var imgList = eachBindDataTag(bindData[bindName].nodes,"img");
  var lastImgList = that.data.imgList;
  if(lastImgList!=undefined){
    imgList=imgList.concat(lastImgList);
  }
  clearImgSrc(imgList);
  that.setData({ imgList: imgList });
  that.setData(bindData)
  that.wxParseImgLoad = wxParseImgLoad;
  that.wxParseImgTap = wxParseImgTap;

}

function clearImgSrc(imgArray){
  
  for (var index = 0; index < imgArray.length; index++) {
    console.log(imgArray)
    var fdStart = imgArray[index].attr.src.indexOf("/");
    if (fdStart == 0 ) {
      var imageIndexOf = imgArray[index].attr.src.indexOf("/") + 1;
      var imageLength = imgArray[index].attr.src.length;
      var image = imgArray[index].attr.src.substring(imageIndexOf, imageLength);
      imgArray[index].attr.src = 'http://hq.centaline.com.cn/' + image;
      imgArray[index].attr.dataSrc = 'http://hq.centaline.com.cn/' + image;

      console.log('http://hq.centaline.com.cn/' + image)

      // 表示strCode是以http://hq.centanet.com开头；
    } else if (fdStart == -1) {
     
      // imgArray[index].attr.src = "";
      // 表示strCode不是以http://hq.centanet.com开头
    }
    console.log(imgArray[index].attr.src)
    // 
    
    
  }   
}

/*HTML文本元素迭代器*/
function eachBindDataTag(nodes, queryDom,selectData){
   var nodes=nodes;
   var targetNodes=new Array();
   var selectTarget=new Array();

   /*拼接上一次迭代元素*/
   if(selectData!=undefined||selectData!=null){
     for (var index = 0; index < selectData.length;index++){
       selectTarget.push(selectData[index]);
    }
   }
   

  // console.log("===上一次迭代元素===");
  // console.log(selectTarget);

   
   /*返回迭代元素*/
   if(nodes.length==0){
   //  console.log("开始返回");
   //  console.log(selectTarget);
     for(var targetIndex=0;targetIndex<selectTarget.length;targetIndex++){
        var indexStr=selectTarget[targetIndex].index;
        var indexArray=indexStr.split('.');
        var nodeName="";
        for(var nodeSpitIndex=0;nodeSpitIndex<indexArray.length;nodeSpitIndex++){
            nodeName=nodeName+"."+"nodes["+indexArray[nodeSpitIndex]+"]";
        }
        
        if(nodeName.indexOf(".")>-1){
          nodeName = nodeName.substring(1);
        }
        nodeName = selectTarget[targetIndex].from + "."+nodeName;
        selectTarget[targetIndex].nodeName=nodeName;
     }

     return selectTarget;
   }
  
   
   /*遍历查找迭代元素*/
   for(var index=0;index<nodes.length;index++){
     //console.log(nodes[index].tag);
     //nodes[index].nodeIndex=index;
     var parsentName;
     if (nodes[index].tag == queryDom){
       selectTarget.push(nodes[index]);
     }

     if (nodes[index].nodeName!=undefined){
       parsentName = nodes[index].nodeName;
     }
     
     if (nodes[index].nodes != undefined) {
       var sonNodes = nodes[index].nodes;

        //console.log("成立的索引是："+i);
        //console.log(sonNodes);
       for (var nodeIndex = 0; nodeIndex < sonNodes.length; nodeIndex++){
       //  console.log(sonNodes[nodeIndex]);
         if(sonNodes[nodeIndex].attr!=undefined&&sonNodes[nodeIndex].attr.src!=undefined){
            sonNodes[nodeIndex].attr.dataSrc=sonNodes[nodeIndex].attr.src;
         }
         
         targetNodes.push(sonNodes[nodeIndex]);
       }
     }
   }
    //console.log("下一批对象");
    //console.log(targetNodes);
   return eachBindDataTag(targetNodes, queryDom, selectTarget);
}


// 图片点击事件
function wxParseImgTap(e) {
  var that = this;
  var nowImgUrl = e.target.dataset.src;
  var tagFrom = e.target.dataset.from;
  
  console.log(that.data[tagFrom].imageUrls)
  for (var index = 0; index < that.data[tagFrom].imageUrls.length; index++) {
    var fdStart = that.data[tagFrom].imageUrls[index].indexOf("/");
    if (fdStart == 0) {
      var imageIndexOf = that.data[tagFrom].imageUrls[index].indexOf("/") + 1;
      var imageLength = that.data[tagFrom].imageUrls[index].length;

      var image = that.data[tagFrom].imageUrls[index].substring(imageIndexOf, imageLength);
      that.data[tagFrom].imageUrls[index] = 'http://hq.centaline.com.cn/' + image;
      // 表示strCode是以http://hq.centanet.com开头；
    } else if (fdStart == -1) {
      // imgArray[index].attr.src = "";
      // 表示strCode不是以http://hq.centanet.com开头
    }
    
    // 


  } 

  
  if (typeof (tagFrom) != 'undefined' && tagFrom.length > 0) {
    console.log(nowImgUrl)
    console.log(that.data[tagFrom].imageUrls)
    wx.previewImage({
      current: nowImgUrl, // 当前显示图片的http链接
      urls: that.data[tagFrom].imageUrls // 需要预览的图片http链接列表
    })
  }
}

/**
 * 图片视觉宽高计算函数区 
 **/
function wxParseImgLoad(e) {
  var that = this;
  var tagFrom = e.target.dataset.from;
  var idx = e.target.dataset.idx;
  if (typeof (tagFrom) != 'undefined' && tagFrom.length > 0) {
    calMoreImageInfo(e, idx, that, tagFrom)
  } 
}
// 假循环获取计算图片视觉最佳宽高
function calMoreImageInfo(e, idx, that, bindName) {
  var temData = that.data[bindName];
  if (!temData || temData.images.length == 0) {
    return;
  }
  var temImages = temData.images;

  //因为无法获取view宽度 需要自定义padding进行计算，稍后处理
  var recal = wxAutoImageCal(e.detail.width, e.detail.height,that,bindName); 
  // temImages[idx].width = recal.imageWidth;
  // temImages[idx].height = recal.imageheight; 
  // temData.images = temImages;
  // var bindData = {};
  // bindData[bindName] = temData;
  // that.setData(bindData);
  var index = temImages[idx].index
  var key = `${bindName}`
  for (var i of index.split('.')) key+=`.nodes[${i}]`
  var keyW = key + '.width'
  var keyH = key + '.height'
  
  that.setData({
    [keyW]: recal.imageWidth,
    [keyH]: recal.imageheight,
  })
}

// 计算视觉优先的图片宽高
function wxAutoImageCal(originalWidth, originalHeight,that,bindName) {
  //获取图片的原始长宽
  var windowWidth = 0, windowHeight = 0;
  var autoWidth = 0, autoHeight = 0;
  var results = {};
  var padding = that.data[bindName].view.imagePadding;
  windowWidth = realWindowWidth-2*padding;
  windowHeight = realWindowHeight;
  //判断按照那种方式进行缩放
  // console.log("windowWidth" + windowWidth);
  if (originalWidth > windowWidth) {//在图片width大于手机屏幕width时候
    autoWidth = windowWidth;
    // console.log("autoWidth" + autoWidth);
    autoHeight = (autoWidth * originalHeight) / originalWidth;
    // console.log("autoHeight" + autoHeight);
    results.imageWidth = autoWidth;
    results.imageheight = autoHeight;
  } else {//否则展示原来的数据
    results.imageWidth = originalWidth;
    results.imageheight = originalHeight;
  }
  return results;
}

function wxParseTemArray(temArrayName,bindNameReg,total,that){
  
  var array = [];
  var temData = that.data;
  var obj = null;
  for(var i = 0; i < total; i++){
    var simArr = temData[bindNameReg+i].nodes;
    array.push(simArr);
  }

  temArrayName = temArrayName || 'wxParseTemArray';
  obj = JSON.parse('{"'+ temArrayName +'":""}');
  obj[temArrayName] = array;
  that.setData(obj);
}

/**
 * 配置emojis
 * 
 */

function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
   HtmlToJson.emojisInit(reg,baseSrc,emojis);
}

 



module.exports = {
  wxParse: wxParse,
  wxParseTemArray:wxParseTemArray,
  emojisInit:emojisInit
}


